package mobi.pooper;

import java.io.IOException;
import java.util.Set;

import mobi.pooper.db.IPicsDbAdapter;
import mobi.pooper.pictures.Picture;

import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;

public class Pooper extends Game {
	public static final int NO = 0;
	public static final int YES = 1;

	private Screen mainMenuScreen;
	private Screen gameScreen;
	private Screen browserScreen;
	private Screen resultScreen;
	private Screen statScreen;

	private Picture rightVariantPicture;

	@Override
	public void create() {

		Assets.checkTasksDb();

		Assets.load();

		mainMenuScreen = new MainMenuScreen(this);
		setScreen(mainMenuScreen);		
	}

	public void startGame(){
		try {
			gameScreen = new GameScreen(this);
			setScreen(gameScreen);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void dispose() {
		Assets.dispose();
	}

	@Override
	public void pause() {
	}

	@Override
	public void resize(int arg0, int arg1) {
	}

	@Override
	public void resume() {
	}

	public void showResult(int result) {
		gameScreen.dispose();
		resultScreen = new ResultScreen(this, result);
		setScreen(resultScreen);

		updateStatistics(result);
	}

	public void resultHaveSeen() {
		resultScreen.dispose();
		startGame();
	}

	public void startPicturesBrowser() {
		try {
			browserScreen = new BrowserScreen(this);
			setScreen(browserScreen);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void startShowingStat() {
		statScreen = new StatScreen(this);
		setScreen(statScreen);
	}

	public void setRightVariant(Set<Picture> pics, int rightVariant) {
		Picture[] pictures = new Picture[pics.size()];
		pics.toArray(pictures);

		rightVariantPicture = pictures[rightVariant];
	}

	private void updateStatistics(int result) {
		if(rightVariantPicture != null){
			IPicsDbAdapter dba = ((IPooperApplication)Gdx.app).getPicsDbAdapter();
			dba.open();
			
			if(result == YES){
				rightVariantPicture.success();
			}else{
				rightVariantPicture.fail();
			}
			
			dba.updateItem(rightVariantPicture);
			dba.close();
		}
	}
}
